package com.kedou.net;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import com.kedou.app.Config;
import com.kedou.app.R;
import com.kedou.domain.User;
import com.kedou.util.Util;

/**
 * 请求后台 获取投资人列表
 * 
 * @author zhouchao
 * 
 */
public class PostFunderList {
	public PostFunderList(String token, String userId, int page, String os,
			String deviceId, final SuccessCallback successCallback,
			final FailCallback failCallback, final Context context) {
		new NetConnection(
				Util.getSDBaseUrl() + Config.URL_FUNDERLIST,
				HttpMethod.POST,
				new NetConnection.SuccessCallback() {

					@Override
					public void onSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							ArrayList<User> users = new ArrayList<User>();
							switch (obj.getInt(Config.KEY_STATUSCODE)) {
							case Config.RESULT_STATUS_SUCCESS:
								if (successCallback != null) {
									if (obj.has("data")) {
										JSONArray jsonArray = obj
												.getJSONArray("data");
										for (int i = 0; i < jsonArray.length(); i++) {
											User user = new User();
											JSONObject jsonUser = (JSONObject) jsonArray
													.get(i);
											if (jsonUser.has("portrait")) {
												user.setPortrait(jsonUser
														.getString("portrait"));
											}
											if (jsonUser.has("userId")) {
												user.setUserId(jsonUser
														.getString("userId"));
											}
											if (jsonUser.has("realName")) {
												user.setRealName(jsonUser
														.getString("realName"));
											}
											users.add(user);
										}
									}
									successCallback.onSuccess(
											obj.getString(Config.KEY_STATUSMSG),
											users);
								}
								break;
							default:
								if (failCallback != null) {
									failCallback.onFail(obj
											.getString(Config.KEY_STATUSMSG));
								}
								break;
							}

						} catch (JSONException e) {
							e.printStackTrace();
							if (failCallback != null) {
								failCallback.onFail(context.getResources()
										.getString(R.string.server_have_wrong));
							}
						}
					}
				}, new NetConnection.FailCallback() {

					@Override
					public void onFail() {
						if (failCallback != null) {
							failCallback.onFail(context.getResources()
									.getString(R.string.server_have_wrong));
						}
					}
				}, Config.KEY_TOKEN, token, Config.KEY_USERID, userId,
				Config.KEY_PAGE, page + "", Config.KEY_OS, os,
				Config.KEY_DEVICE, deviceId);
	}

	public static interface SuccessCallback {
		void onSuccess(String msg, ArrayList<User> mUsers);
	}

	public static interface FailCallback {
		void onFail(String msg);
	}
}
